package com.example.utils;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Enumeration;

/**
 * @author ZZZ
 * @version 1.0
 * @date 2019/10/28 0028
 */
public class WebUtils {

    private WebUtils() {
    }


    /**
     * 获取本机IP地址
     *
     * @return
     */
    public static String getServerIp() {
        String serverIp = null;
        try {
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                ip = ni.getInetAddresses().nextElement();
                serverIp = ip.getHostAddress();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                        && !ip.getHostAddress().contains(":")) {
                    serverIp = ip.getHostAddress();
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return serverIp;
    }

    /**
     * 获取登录用户的IP地址
     *
     * @return
     */
    public static String getIpAddr() {
        HttpServletRequest request = SpringTool.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 获取浏览器信息
     *
     * @return
     */
    public static String getBrowserUA() {
        HttpServletRequest request = SpringTool.getRequest();
        return request.getHeader("User-Agent");
    }


    /**
     * 响应数据给浏览器
     *
     * @param response
     * @param errorMsg
     * @throws IOException
     */
    public static void responseData(ServletResponse response, String errorMsg, Integer statusCode) throws
            IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(statusCode);
        httpResponse.setContentType("application/json");
        httpResponse.setCharacterEncoding("utf-8");
        httpResponse.getWriter().write(errorMsg);
        httpResponse.getWriter().close();
    }


    /**
     * 响应成功数据
     *
     * @param response
     * @param errorMsg
     * @throws IOException
     */
    public static void responseSuccessData(ServletResponse response, String errorMsg) throws IOException {
        responseData(response, errorMsg, HttpServletResponse.SC_OK);
    }


    /**
     * 响应错误数据
     *
     * @param response
     * @param errorMsg
     * @throws IOException
     */
    public static void responseErrorData(ServletResponse response, String errorMsg) throws IOException {
        responseData(response, errorMsg, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }


    /**
     * 添加跨域请求头
     *
     * @param httpServletRequest
     * @param httpServletResponse
     */
    public static void setCorsHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String host = httpServletRequest.getHeader("Origin");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", host);
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "content-type, authorization, x-requested-with");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
    }


    /**
     * 下载设置
     *
     * @param response
     * @param exportData
     */
    public static void downloadConfig(HttpServletResponse response, File exportData) {
        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(exportData.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            response.setHeader("Content-Disposition", "attachment; filename=" + exportData.getName());
        }
        response.setContentLengthLong(exportData.length());
        // 实现文件下载
        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(exportData);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        System.out.println(getServerIp());
    }


}
